package fun.coding.postform;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


public class PostForm {
	public static final String S3_KEY = "testS3xiaoyshi.txt";
	public static final String FILE_PATH = "/home/local/ANT/xiaoyshi/workspaceFun/brain-code-jam/";
	public static final String S3_BUCKET = "s3-bucket";
	private static final String S3_AMAZON_NINJA_ENDPOINT = "https://improvement-ninjas.amazon.com/s3files/s3put.cgi";
	private static final String S3_NINJA_FILE_PATH = "https://improvement-ninjas.amazon.com/s3files/s3get.cgi/AFTRaft_LOG_B0C91004251608EK_2013_6_20_11_42_54";
	private static final String TEST_VOGELLA_URL = "http://www.vogella.com";
	private static final String OWNER = "AFTRaftTest";
	
    public static void main(String[] args) {

   //     tryHttpGetGoogleSearch();
        try {
     //       sendPostToPlusKidWeb();
            //trySinglePost();
        //	System.out.println(getFileSize());
        //	sendPostUseS3Proxy();
        //	sendPostToNinjaRaftVersion();
        	sendGetRequest();
        } catch (Exception e) {
            System.out.println("Duh.. " + e.getStackTrace());
            e.printStackTrace();
        } 
        
        System.out.println("Main Done");
    }
    
    public static void sendGetRequest() throws Exception {
    	HttpClient httpClient = HttpClientFactory.getHttpClient();
    	
    	//HttpGet getRequest = new HttpGet(S3_NINJA_FILE_PATH);
    // Following code works perfectly fine. 
    	HttpGet getRequest = new HttpGet(TEST_VOGELLA_URL);
    	
    	HttpResponse response = httpClient.execute(getRequest);
    	
    	BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    	String line = "";
    	
    	while ((line = rd.readLine()) != null) {
    		System.out.println(line);
    	}
    	
    	System.out.println(response.getStatusLine().getStatusCode());
    	
    }
    
    public static void sendPostToNinjaRaftVersion() throws Exception {
    	
        // Creating an HTTPClient
        HttpClient httpClient = HttpClientFactory.getHttpClient();

        //Creating a File using the given filePath
        File file = new File(FILE_PATH, S3_KEY);

        // HttpPost sends a post request to the S3 website
        HttpPost postRequest = new HttpPost(S3_AMAZON_NINJA_ENDPOINT);

        // Creating and filling a MultipartEntity to complete the HTML
        // form on the S3 website
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        reqEntity.addPart("file", new FileBody(file));
        reqEntity.addPart("comment", new StringBody(""));
        reqEntity.addPart("user", new StringBody(OWNER));
        reqEntity.addPart("s3key", new StringBody(S3_KEY));

        // Assigning the Multipart entity to the HttpPost request and
        // executing the request
        postRequest.setEntity(reqEntity);

        httpClient.execute(postRequest);

    }
    
    
    public static void sendPostUseS3Proxy() {
        String url = "http://devtools-s3proxy-sea.amazon.com/s3proxy/put";
        HttpPost httppost = new HttpPost(url);
        
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        
        nameValuePairs.add(new BasicNameValuePair("s3key", S3_KEY));
        nameValuePairs.add(new BasicNameValuePair("length", Long.valueOf(getFileSize()).toString()));
        // This seems not working with perl $file = [$file]
        nameValuePairs.add(new BasicNameValuePair("file", FILE_PATH));
        nameValuePairs.add(new BasicNameValuePair("bucket", S3_BUCKET));
        
        try {
        	UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs);
        	entity.setContentType("multipart/form-data");
        	
        	httppost.setEntity(entity);
        	HttpClient httpclient = new DefaultHttpClient();
        
        	HttpResponse response = httpclient.execute(httppost);

        	HttpEntity resEntity = response.getEntity();

        	System.out.println("----------------------------------------");
        	System.out.println(response.getStatusLine());
        	if (resEntity != null) {
        		System.out.println("Response content length: " + resEntity.getContentLength() + ", " + resEntity.getContent() + 
        				", " + resEntity.getContentEncoding());
        	}
        	EntityUtils.consume(resEntity);
        } catch (Exception e) {
        	System.err.println("Error in sendPostUseS3Proxy " + e.getStackTrace());
        }

    }
    
    private static long getFileSize() {
    	File f = new File(FILE_PATH);
    	return f.length();
    }
    
    public static void sendPostToPlusKidWeb() throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        try {
            // real URL:
            // http://en.blog.wordpress.com/2012/05/23/summer-food-blogs/comment-page-2/?blogsub=confirming#subscribe-blog
            String url = "https://subscribe.wordpress.com";
            HttpPost httppost = new HttpPost(url);
            
            //StringBody author = new StringBody("test11");
            StringBody email = new StringBody("shixiaoyu.zju@gmail.com");
//            StringBody comment = new StringBody("A binary file of some kind. This is really nice written blog");
//            StringBody recaptcha_response_field = new StringBody("uramepr sorrow");
//            
            MultipartEntity reqEntity = new MultipartEntity();
            
            //reqEntity.addPart("author", author);
            reqEntity.addPart("email", email);
//            reqEntity.addPart("comment", comment);
//            reqEntity.addPart("recaptcha_response_field", recaptcha_response_field);

            httppost.setEntity(reqEntity);

            System.out.println("executing request " + httppost.getRequestLine());
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity resEntity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength() + ", " + resEntity.getContent() + 
                        ", " + resEntity.getContentEncoding());
            }
            EntityUtils.consume(resEntity);
        } finally {
            try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {}
        }

    }
    
    // here is a nice tutorial
    // http://www.vogella.com/articles/ApacheHttpClient/article.html
    public static void trySinglePost() {
        try {
            //URIBuilder builder = new URIBuilder();
            //builder.setScheme("https").setHost("subscribe.wordpress.com");
            //URI uri = builder.build();
            String uri = "https://subscribe.wordpress.com";
            HttpPost httppost = new HttpPost(uri);
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            // id maybe ?subscribe-field-3
           
            nameValuePairs.add(new BasicNameValuePair("email", "shixiaoyu.zju@gmail.com"));
            
            nameValuePairs.add(new BasicNameValuePair("action", "subscribe"));
            nameValuePairs.add(new BasicNameValuePair("blog_id", "3584907"));
            nameValuePairs.add(new BasicNameValuePair("source", "http://en.blog.wordpress.com/2009/01/09/subscribe-to-comments/?blogsub=confirming"));
            nameValuePairs.add(new BasicNameValuePair("redirect_fragment", ""));
            nameValuePairs.add(new BasicNameValuePair("_wpnonce", "5cb4ba5816"));
            
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            
            System.out.println(httppost.getURI());
            
            HttpClient httpclient = new DefaultHttpClient();
            
            HttpResponse response = httpclient.execute(httppost);
            
            HttpEntity resEntity = response.getEntity();

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength() + ", " + resEntity.getContent() + 
                        ", " + resEntity.getContentEncoding());
            }
            EntityUtils.consume(resEntity);
            
        } catch (Exception e) {
            System.err.println("Some exception from trySinglePost" + e.getStackTrace());
        }
    }
    
    public static void tryHttpGetGoogleSearch() {
        try {
            URIBuilder builder = new URIBuilder();
            builder.setScheme("http").setHost("www.google.com").setPath("/search")
                .setParameter("q", "xiaoyu shi")
                .setParameter("btnG", "Google Search")
                .setParameter("aq", "f")
                .setParameter("oq", "");
            URI uri = builder.build();
            HttpGet httpget = new HttpGet(uri);
            System.out.println(httpget.getURI());
            
            //HttpResponse response = 
        } catch (Exception e) {
            System.err.println("Some exception from tryHttpGetGoogleSearch" + e.getStackTrace());
        }
    }
    
    public static void tryHttpPost() {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.google.com");

        // Request parameters and other properties.
        List<NameValuePair> params = new ArrayList<NameValuePair>(2);
        params.add(new BasicNameValuePair("search", "12345"));
        //params.add(new BasicNameValuePair("param-2", "Hello!"));
        //httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

        //Execute and get the response.
        try {
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
    
            System.out.println("status code is " + response.getStatusLine().getStatusCode());
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    System.out.println(entity.getContent());
                } finally {
                    instream.close();
                }
            }
        } catch (Exception e) {
            System.err.println("Some exception " + e.getStackTrace());
        }        
    }
}
